import datetime

import pandas as pd
from loguru import logger

from config import ROOT_DIR
from utils.strategy.conf.base import BaseConf, kline_map
import os
from utils.data.sqlLoader import loader_mapper
from utils.data.loader import BaseLoader
from config import DATABASE_TYPE


class BtConf(BaseConf):

    def load_data(self) -> pd.DataFrame:
        loader: BaseLoader = loader_mapper[DATABASE_TYPE](0, 1, self.period, symbols=self.strategy.symbols,
                                              batch_size=self.strategy.KlineBatchSize)
        s: int = int(
            self.s_time.timestamp()) - self.period * self.strategy.historyKlineCount * self.strategy.KlineBatchSize
        s: str = datetime.datetime.fromtimestamp(s, tz=datetime.timezone.utc).strftime('%Y-%m-%d_%H-%M-%S')
        e: str = self.e_time.strftime('%Y-%m-%d_%H-%M-%S')
        data_file = f'''{self.period}_{self.strategy.KlineBatchSize}_{s}_{e}_{'-'.join(self.strategy.symbols)}.pickle'''
        if not os.path.exists(os.path.join(ROOT_DIR, 'locals/data', data_file)):
            df = loader.fetch(
                int(self.s_time.timestamp()) - self.period * self.strategy.historyKlineCount * self.strategy.KlineBatchSize,
                end=int(self.e_time.timestamp()))
            df.drop_duplicates(subset=['open_time', 'symbol', 'trade_type'], inplace=True)
            df.sort_values(by=['open_time', 'symbol'], inplace=True)
            df.to_pickle(os.path.join(ROOT_DIR, 'locals/data', data_file))
        else:
            return pd.read_pickle(os.path.join(ROOT_DIR, 'locals/data', data_file))
        return df


    def __str__(self):
        return self.strategy.system_conf.__str__()
